package com.example.novelweb.config;

import com.example.novelweb.constant.RedisConstant;
import com.example.novelweb.service.CommentService;
import com.example.novelweb.service.NovelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Set;

@Component
@Slf4j
public class CommentLikesTask {

  @Resource
  private StringRedisTemplate stringRedisTemplate;
  @Resource
  private CommentService commentService;

  /**
   * 定时执行 同步评论点赞数
   * */
  @Scheduled(cron = "0 */15 * * * *") //每15min执行一次
//  @Scheduled(cron = "0 0 */2 * * *") //每2小时执行一次
  public void syncNovelCollectNum() {
    log.info("======Start 同步comment.likes=========");
    Set<String> keys = stringRedisTemplate.keys(RedisConstant.KEY_COMMENT_LIKE_NUM+"*");
    if(keys !=null) {
      for (String key : keys) {
        Long commentId = Long.parseLong(key.substring(RedisConstant.KEY_COMMENT_LIKE_NUM.length()));
        long curNum = Long.parseLong(Objects.requireNonNull(stringRedisTemplate.opsForValue().get(key)));
        if(curNum != 0) {
          commentService.updateLikesByAdd(commentId,curNum);
        }
        stringRedisTemplate.delete(key);
      }
    }
    log.info("======END 同步comment.likes===========");

  }


}
